package com.srp.backend.controller;

import com.srp.backend.common.Result;
import com.srp.backend.service.FileDownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件下载控制器
 */
@RestController
@RequestMapping("/api/download")
@CrossOrigin(origins = "*")
public class FileDownloadController {
    
    @Autowired
    private FileDownloadService fileDownloadService;
    
    /**
     * 按文件名下载文件
     * @param fileName 文件名，例如 result.docx 或 result.xlsx
     * @return 文件资源
     */
    @GetMapping("/file/{fileName}")
    public ResponseEntity<Resource> downloadFileByName(@PathVariable String fileName, HttpServletRequest request) {
        try {
            Resource resource = fileDownloadService.loadFileByName(fileName);
            return prepareFileResponse(resource, request);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 直接下载结果文件（Word格式）
     * @return 文件资源
     */
    @GetMapping("/result/word")
    public ResponseEntity<Resource> downloadResultWord(HttpServletRequest request) {
        try {
            Resource resource = fileDownloadService.loadResultWordFile();
            return prepareFileResponse(resource, request);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 直接下载结果文件（Excel格式）
     * @return 文件资源
     */
    @GetMapping("/result/excel")
    public ResponseEntity<Resource> downloadResultExcel(HttpServletRequest request) {
        try {
            Resource resource = fileDownloadService.loadResultExcelFile();
            return prepareFileResponse(resource, request);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取可用的结果文件列表
     * @return 可下载文件列表
     */
    @GetMapping("/results")
    public Result<Object> getResultFiles() {
        try {
            return Result.success(fileDownloadService.getResultFiles());
        } catch (Exception e) {
            return Result.error("获取结果文件列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 下载转换后的文件（Word格式）
     * @param uuid 文件处理的UUID
     * @return 文件资源
     */
    @GetMapping("/word/{uuid}")
    public ResponseEntity<Resource> downloadWordFile(@PathVariable String uuid, HttpServletRequest request) {
        try {
            Resource resource = fileDownloadService.loadWordFileAsResource(uuid);
            return prepareFileResponse(resource, request);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 下载转换后的文件（Excel格式）
     * @param uuid 文件处理的UUID
     * @return 文件资源
     */
    @GetMapping("/excel/{uuid}")
    public ResponseEntity<Resource> downloadExcelFile(@PathVariable String uuid, HttpServletRequest request) {
        try {
            Resource resource = fileDownloadService.loadExcelFileAsResource(uuid);
            return prepareFileResponse(resource, request);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 下载可视化结果图片
     * @param uuid 文件处理的UUID
     * @param page 页码
     * @return 图片资源
     */
    @GetMapping("/visual/{uuid}/{page}")
    public ResponseEntity<Resource> downloadVisualImage(
            @PathVariable String uuid, 
            @PathVariable int page,
            HttpServletRequest request) {
        try {
            Resource resource = fileDownloadService.loadVisualImageAsResource(uuid, page);
            return prepareFileResponse(resource, request);
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 获取可用的下载文件列表
     * @param uuid 文件处理的UUID
     * @return 可下载文件列表
     */
    @GetMapping("/files/{uuid}")
    public Result<Object> getDownloadableFiles(@PathVariable String uuid) {
        try {
            return Result.success(fileDownloadService.getDownloadableFiles(uuid));
        } catch (Exception e) {
            return Result.error("获取可下载文件列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 准备文件响应
     */
    private ResponseEntity<Resource> prepareFileResponse(Resource resource, HttpServletRequest request) throws IOException {
        // 确定文件的内容类型
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            // 无法确定文件类型
        }
        
        // 如果无法确定内容类型，则默认为二进制流
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }
}